package com.shinhye.elephantsafe.recevier;

import com.shinhye.elephantsafe.R;
import com.shinhye.elephantsafe.service.UpdateWidgetService;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class ESafeWidget extends AppWidgetProvider {
	private String TAG = "ESafeWidget";

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
		System.out.println(TAG + "::onDeleted");
	}

	@Override
	public void onDisabled(Context context) {
		super.onDisabled(context);
		System.out.println(TAG + "::onDisabled");

		Intent intent = new Intent(context, UpdateWidgetService.class);
		context.stopService(intent);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		System.out.println(TAG + "::onUpdate");
		
        // Perform this loop procedure for each App Widget that belongs to this provider         
		for (int i = 0; i < appWidgetIds.length; i++) {
        	int appWidgetId = appWidgetIds[i];              
//        	System.out.println(i + ":::" + appWidgetIds.length);
        	// Create an Intent to launch ExampleActivity             
        	Intent intent = new Intent("com.shinhye.widgetkillprocess");
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0x001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        	// Get the layout for the App Widget and attach an on-click listener             
        	// to the button             
        	RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_elephantsafe);             
        	views.setOnClickPendingIntent(R.id.btn_widget_kill, pendingIntent);              
        	// Tell the AppWidgetManager to perform an update on the current app widget             
        	appWidgetManager.updateAppWidget(appWidgetId, views);         
        }
        
		Intent intent = new Intent(context, UpdateWidgetService.class);
		context.startService(intent);
	}

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		System.out.println(TAG + "::onEnabled");
		
		Intent intent = new Intent(context, UpdateWidgetService.class);
		context.startService(intent);
	}

}
